﻿
namespace SistemaLogistica.Windows.Forms.Almacen.Operaciones
{
    using System;
    using System.Data.Linq;
    using System.Drawing;
    using System.Windows.Forms;
    using EDOSwit.Controls.DataGridView;
    using EDOSwit.Controls.Helpers;
    using EDOSwit.Controls.Types;
    using EDOSwit.Controls.UserControls;
    using SistemaLogistica.Business.Entities;
    using SistemaLogistica.Business.Entities.Types;
    using SistemaLogistica.Business.Logic;
    using SistemaLogistica.Windows.Helpers;

    public partial class CwfGuiaRemision : MaestroDetalleSeguro, IRefrescar
    {
        public CwfGuiaRemision()
        {
            InitializeComponent();
            this.dgvDetalle.DataGridView.KeyDown += new KeyEventHandler(DataGridView_KeyDown);
        }

        protected override void CellPainting(ref DataGridViewCellPaintingEventArgs e)
        {
            Graphics g = e.Graphics;
            bool selected = ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected);
            Color fcolor = (selected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor);
            Color bcolor = (selected ? e.CellStyle.SelectionBackColor : e.CellStyle.BackColor);
            Font font = e.CellStyle.Font;
            font = new Font("Tahoma", 7);

            GuiaRemision guiaRemision = this.MaestroBindingSource[e.RowIndex] as GuiaRemision;

            if (guiaRemision != null)
            {
                int x = e.CellBounds.Left + e.CellStyle.Padding.Left;
                int y = e.CellBounds.Top + e.CellStyle.Padding.Top;
                int width = e.CellBounds.Width - (e.CellStyle.Padding.Left + e.CellStyle.Padding.Right);
                int height = 13 + (e.CellStyle.Padding.Top + e.CellStyle.Padding.Bottom);

                g.FillRectangle(new SolidBrush(bcolor), e.CellBounds);
                y = y + height - 1;

                if (e.ColumnIndex == 0)
                {
                    font = new Font("Tahoma", 8, FontStyle.Bold);

                    if (selected)
                        TextRenderer.DrawText(e.Graphics, "Nº: " + guiaRemision.IdGuiaRemision.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, "Nº: " + guiaRemision.IdGuiaRemision.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 7);
                    y = y + height - 1;
                }
                else
                {
                    font = new Font("Tahoma", 9, FontStyle.Bold);

                    if (selected)
                        TextRenderer.DrawText(e.Graphics, "F: " + guiaRemision.Fecha.ToShortDateString(), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, "F: " + guiaRemision.Fecha.ToShortDateString(), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 7);
                    y = y + height - 1;
                }
            }
        }

        private void DataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.dgvDetalle.DataGridView.CurrentCell != null)
                {
                    if (Mensaje.ShowMessageConfirm(this.ParentForm, Constantes.TituloMensaje, "¿Desea eliminar el Detalle?") == DialogResult.No)
                    {
                        e.Handled = true;
                    }
                    else
                    {
                        this.dgvDetalle.DataGridView.Rows.Remove(this.dgvDetalle.DataGridView.CurrentRow);
                        if (this.dgvDetalle.DataGridView.Rows.Count == 0)
                        {
                            this.dgvDetalle.DataGridView.Rows.Add();
                        }
                    }
                }
            }
        }

        protected override void LoadPermisos()
        {
            this.TsMenu.Permisos.AddRange(Metodos.GetPermisos(Convert.ToByte(this.Tag)));
        }

        protected override void FocusKeyPress(object sender, KeyPressEventArgs e)
        {
            base.FocusKeyPress(sender, e);
        }

        protected override void InitialLoad()
        {
            this.cmbDocumento.DisplayMember = "IdDocumento";
            this.cmbDocumento.ValueMember = "IdDocumento";
            lblUsuario.Text = Empresa.Usuario.Nombre;
            lblUsuario.Tag = Empresa.Usuario.IdEmpleado;
            this.cmbTipo.DataSource = Enum.GetNames(typeof(GuiaType));
            this.cmbTipos.DataSource = Enum.GetNames(typeof(GuiaType));

            this.MaestroBindingSource.DataSource = GuiaRemisionManager.Instancia.Listar();
            this.dgvMaestro.DataSource = this.MaestroBindingSource;
            LoadDataGridView();
            OcultarColumnas();
        }

        private void cmbTipo_SelectionChangeCommitted(object sender, EventArgs e)
        {
            this.cmbDocumento.Text = string.Empty;
            if (this.cmbTipo.SelectedIndex == 0)
            {
                this.cmbDocumento.DataSource = NotaIngresoManager.Instancia.ListarPorGuia(GuiaRemisionManager.Instancia.ListarIDsPorTipo(this.cmbTipo.SelectedIndex));
            }
            else if (this.cmbTipo.SelectedIndex == 1)
            {
                this.cmbDocumento.DataSource = NotaSalidaManager.Instancia.ListarPorGuia(GuiaRemisionManager.Instancia.ListarIDsPorTipo(this.cmbTipo.SelectedIndex));
            }
            cmbDocumento_SelectedIndexChanged(sender, EventArgs.Empty);
        }

        private void cmbDocumento_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbDocumento.SelectedIndex != -1)
            {
                if (this.cmbTipo.SelectedIndex == 0)
                {
                    NotaIngreso miNotaIngreso = NotaIngresoManager.Instancia.ObtenerPorID(Convert.ToInt32(this.cmbDocumento.Text));
                    this.txtDestino.Text = Empresa.Direccion;
                    this.txtOrigen.Text = miNotaIngreso.Factura.OrdenCompra.Proveedor.Direccion;
                    loadNotaIngreso(miNotaIngreso);
                }
                else if (this.cmbTipo.SelectedIndex == 1)
                {
                    NotaSalida miNotaSalida = NotaSalidaManager.Instancia.ObtenerPorID(Convert.ToInt32(this.cmbDocumento.Text));
                    this.txtDestino.Text = miNotaSalida.OrdenPedido.Pedido.Area.Ubigeo + "-" + miNotaSalida.OrdenPedido.Pedido.Area.Ubicacion;
                    this.txtOrigen.Text = Empresa.Direccion;
                    loadNotaSalida(miNotaSalida);
                }
            }
            else
            {
                this.txtOrigen.Text = string.Empty;
                this.txtDestino.Text = string.Empty;
                LoadDataGridView();
            }
        }

        private void loadNotaIngreso(NotaIngreso notaIngreso)
        {
            if (notaIngreso != null)
            {
                int index = 0;
                this.dgvDetalle.DataGridView.Rows.Clear();
                foreach (DetalleNotaIngreso d in notaIngreso.Detalle)
                {
                    index = this.dgvDetalle.DataGridView.Rows.Add(1);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = d.Bien.Nombre;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Tag = d.Bien.IdBien;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Value = d.Bien.UnidadMedidia.Abreviatura;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[2].Value = d.Cantidad;
                }
                this.dgvDetalle.DataGridView.Rows.Add();
            }
        }

        private void loadNotaSalida(NotaSalida notaSalida)
        {
            if (notaSalida != null)
            {
                int index = 0;
                this.dgvDetalle.DataGridView.Rows.Clear();
                foreach (DetalleNotaSalida d in notaSalida.Detalle)
                {
                    index = this.dgvDetalle.DataGridView.Rows.Add(1);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = d.Bien.Nombre;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Tag = d.Bien.IdBien;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Value = d.Bien.UnidadMedidia.Abreviatura;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[2].Value = d.Cantidad;
                }
                this.dgvDetalle.DataGridView.Rows.Add();
            }
        }

        private void LoadDataGridView()
        {
            this.dgvDetalle.DataGridView.Rows.Clear();
            this.dgvDetalle.DataGridView.Columns.Clear();
            this.dgvDetalle.Mode = Mode.ReadOnly;

            CustomColumnDataGridView colummn = new CustomColumnDataGridView();
            colummn.Name = "Bien";
            colummn.HeaderText = "Bien";
            colummn.Width = 300;
            colummn.ControlType = CustomControlType.FindDropDownList;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);
            colummn.ColumnNext = 2;

            colummn = new CustomColumnDataGridView();
            colummn.Name = "UnidadMedida";
            colummn.HeaderText = "UnidadMedida";
            colummn.ControlType = CustomControlType.TextBox;
            colummn.ReadOnly = true;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Cantidad";
            colummn.HeaderText = "Cantidad";
            colummn.Width = 80;
            colummn.ControlType = CustomControlType.TextBox;
            colummn.DataType = DataType.Decimales;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            this.dgvDetalle.DataGridView.Rows.Add();
            this.dgvDetalle.DataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        private GuiaRemision GetGuiaRemision()
        {
            GuiaRemision guiaRemision = new GuiaRemision
            {
                IdGuiaRemision = Convert.ToInt32(this.identificador),
                IdDocumento = Convert.ToInt32(this.cmbDocumento.Text),
                Empleados = new Empleados { IdEmpleado = Empresa.Usuario.IdEmpleado },
                Origen = this.txtOrigen.Text,
                Destino = this.txtDestino.Text,
                Descripcion = this.txtDescripcion.Text,
                Motivo = this.txtMotivo.Text,
                Transporte = this.txtTransporte.Text,
                Fecha = this.dtpFechaEmision.Value,
                FechaTranslado = dtpFechaTraslado.Value,
                TipoGuia = this.cmbTipo.SelectedIndex
            };
            foreach (DataGridViewRow row in this.dgvDetalle.DataGridView.Rows)
            {
                if (ValidateData(row.Index))
                {
                    guiaRemision.Detalle.Add(new DetalleGuiaRemision
                    {
                        Bien = new Bien { IdBien = Convert.ToInt32(row.Cells[0].Tag) },
                        Cantidad = Convert.ToDecimal(row.Cells[2].Value),
                    });
                }
            }
            return guiaRemision;
        }

        private bool ValidateData(int rowIndex)
        {
            bool result = true;

            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[0].Tag == null)
            {
                result = false;
            }
            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[2].Value == null)
            {
                result = false;
            }
            return result;
        }

        protected override bool ValidateData()
        {
            bool result = true;

            if (this.cmbTipo.SelectedIndex == -1)
            {
                this.errValidator.SetError(this.cmbTipo, "Seleccionar Tipo.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.cmbTipo, string.Empty);
            }
            if (string.IsNullOrEmpty(this.cmbDocumento.Text.Trim()))
            {
                this.errValidator.SetError(this.cmbDocumento, "Seleccionar Documento.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.cmbDocumento, string.Empty);
            }
            if (this.dtpFechaTraslado.Value < this.dtpFechaEmision.Value)
            {
                this.errValidator.SetError(this.dtpFechaTraslado, "Debe cumplir fecha de emision < fecha de transalado.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.dtpFechaTraslado, string.Empty);
            }
            int contador1 = 0;
            int contador2 = 0;
            foreach (DataGridViewRow row in dgvDetalle.DataGridView.Rows)
            {
                if (row.Cells[0].Tag == null) continue;
                if (ValidateData(row.Index)) contador1++;
                else contador2++;
            }
            if (!(contador1 != 0 && contador2 == 0 && dgvDetalle.DataGridView.Rows.Count > 0))
            {
                Mensaje.ShowMessageAlert(this.ParentForm, Constantes.TituloMensaje, "Debe existir proudctos e ingresados correctamente.");
                result = false;
            }
            return result;
        }

        protected override void ClearControls()
        {
            this.identificador = 0;
            LoadDataGridView();
            base.ClearControls();
        }

        protected override bool SaveData()
        {
            bool result = false;
            int posicion = this.MaestroBindingSource.Position;

            try
            {
                switch (this.estadoActual)
                {
                    case EstadoActual.Nuevo:
                        GuiaRemisionManager.Instancia.Registrar(GetGuiaRemision());
                        break;
                    case EstadoActual.Editar:
                        GuiaRemisionManager.Instancia.Modificar(GetGuiaRemision());
                        break;
                    case EstadoActual.Eliminar:
                        GuiaRemisionManager.Instancia.Eliminar(Convert.ToInt32(this.identificador));
                        this.MaestroBindingSource.RemoveCurrent();
                        posicion -= 1;
                        break;
                }
                result = true;
                InitialLoad();
                this.MaestroBindingSource.Position = posicion;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, Constantes.TituloMensaje, ex.Message);
            }
            return result;
        }

        private void OcultarColumnas()
        {
            this.dgvMaestro.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dgvMaestro.Columns["Motivo"].Visible = false;
            this.dgvMaestro.Columns["FechaTranslado"].Visible = false;
            this.dgvMaestro.Columns["Origen"].Visible = false;
            this.dgvMaestro.Columns["Destino"].Visible = false;
            this.dgvMaestro.Columns["Transporte"].Visible = false;
            this.dgvMaestro.Columns["Descripcion"].Visible = false;
            this.dgvMaestro.Columns["IdDocumento"].Visible = false;
            this.dgvMaestro.Columns["TipoGuia"].Visible = false;
            this.dgvMaestro.Columns["Empleados"].Visible = false;
            this.dgvMaestro.Columns["IdGuiaRemision"].HeaderText = "GuiaRemision";
        }

        protected override void EventoNuevo()
        {
            this.cmbDocumento.Enabled = true;
            this.cmbDocumento.Text = "";
            this.cmbTipo.Focus();
        }

        protected override void EventoEditar()
        {
            this.cmbDocumento.Enabled = false;
            this.cmbTipo.Focus();
        }

        protected override void EventoGuardar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void EventoCancelar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void LoadData(object obj)
        {
            GuiaRemision guiaRemision = obj as GuiaRemision;
            if (guiaRemision != null)
            {
                this.identificador = guiaRemision.IdGuiaRemision;
                this.cmbTipo.SelectedIndex = guiaRemision.TipoGuia;
                this.cmbDocumento.Text = guiaRemision.IdDocumento.ToString();
                this.txtOrigen.Text = guiaRemision.Origen;
                this.txtDestino.Text = guiaRemision.Destino;
                this.dtpFechaEmision.Value = guiaRemision.Fecha;
                this.dtpFechaTraslado.Value = guiaRemision.FechaTranslado;
                this.txtTransporte.Text = guiaRemision.Transporte;
                this.txtMotivo.Text = guiaRemision.Motivo;
                this.txtDescripcion.Text = guiaRemision.Descripcion;
                this.lblUsuario.Text = guiaRemision.Empleados.Nombre;
                this.lblUsuario.Tag = guiaRemision.Empleados.IdEmpleado;
                int index = 0;
                this.dgvDetalle.DataGridView.Rows.Clear();
                foreach (DetalleGuiaRemision d in guiaRemision.Detalle)
                {
                    index = this.dgvDetalle.DataGridView.Rows.Add(1);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = d.Bien.Nombre;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Tag = d.Bien.IdBien;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Value = d.Bien.UnidadMedidia.Abreviatura;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[2].Value = d.Cantidad;
                }
                this.dgvDetalle.DataGridView.Rows.Add();
            }
        }

        private void cmbTipos_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.MaestroBindingSource.DataSource = GuiaRemisionManager.Instancia.ListarPorTipo(Convert.ToInt32(this.cmbTipos.SelectedIndex));
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
                this.dgvMaestro.Focus();
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
        }

        #region Miembros de IRefrescar

        public void Refrescar()
        {
            InitialLoad();
        }

        #endregion
    }
}
